package com.beijing.demo.listnode;

/**
 * 曹旭
 * 2025/4/27
 * 分隔链表
 * https://leetcode.cn/problems/partition-list/
 * 给你一个链表的头节点 head 和一个特定值 x ，请你对链表进行分隔，使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
 * 你应当 保留 两个分区中每个节点的初始相对位置。
 */
public class Solution {
    /**
     * 思路:
     * 保留大头 大尾
     * 保留小头 小尾
     * @param head
     * @param x
     * @return
     */
    public static ListNode partition(ListNode head, int x) {
        if(head == null){
            return head;
        }
        ListNode bigNode = null;
        ListNode bigTail = null;
        ListNode smallNode = null;
        ListNode smallTail = null;
        ListNode cur = head;
        while(cur != null){
            if(cur.val >= x){
                if(bigNode == null){
                    bigNode = cur;
                    bigTail = bigNode;
                }else {
                    bigTail.next = cur;
                    bigTail = bigTail.next;
                }
            }else {
                if(smallNode == null){
                    smallNode = cur;
                    smallTail = smallNode;
                }else {
                    smallTail.next = cur;
                    smallTail = smallTail.next;
                }
            }
            cur = cur.next;
        }
        if(smallNode == null){
            return bigNode;
        }
        smallTail.next = bigNode;
        return smallNode;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l4 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        ListNode l2 = new ListNode(2);
        ListNode l5 = new ListNode(5);
        ListNode l22 = new ListNode(2);
        l1.next = l4;
        l4.next = l3;
        l3.next = l2;
        l2.next = l5;
        l5.next = l22;
        partition(l1,3);
    }
}






















